const auth = require('./utils/auth')

App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    
    // 初始化云开发
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: 'cloud1-9gtq8ywcbc4df512',
        traceUser: true,
      })
      
      // 获取用户信息
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: res => {
                this.globalData.userInfo = res.userInfo
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              }
            })
          }
        }
      })
    }
    
    // 获取系统信息
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = capsule;
        this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
      }
    })
  },
  
  // 检查用户认证状态
  checkUserAuth() {
    return new Promise((resolve, reject) => {
      auth.checkAuthentication()
        .then(user => {
          auth.setCurrentUser(user)
          resolve(user)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  
  // 显示认证弹窗
  showAuthModal(userInfo) {
    return auth.showAuthModal(userInfo)
  },
  
  globalData: {
    userInfo: null,
    currentUser: null,
    openid: null,
    // 云开发环境
    env: 'cloud1-9gtq8ywcbc4df512'
  }
})